There's a type
defined like this: type ComponentType = 'CPU' | 'Motherboard' | 'Memory' | 'PSU'
.
I want to create an object that I can use to map a ComponentType
to display strings, e.g. something like:
const componentTypeToLabel/*: to do*/ = {
CPU: 'Computer processing unit',
Motherboard: 'Motherboard',
Memory: 'Memory',
PSU: 'Power supply unit',
};
On additional consideration, however, is that this componentTypeToLabel
will not contain all the possible values of ComponentType
, only some.
What does the type definition look like for componentTypeToLabel
? How do I define that type? I'm aware of how to do it if ComponentType
is an enum
instead (believe it would be const componentTypeToLabel: { [key in ComponentType]? : string } = ...
), but not when ComponentType
is a string union type
.
jcalz :
The type you're looking for is Partial<Record<ComponentType, string>>, or equivalently, {[K in ComponentType]?: string}:\n\ntype ComponentType = 'CPU' | 'Motherboard' | 'Memory' | 'PSU';\nconst componentTypeToLabel: Partial<Record<ComponentType, string>> = {\n CPU: 'Computer processing unit',\n Motherboard: 'Motherboard',\n Memory: 'Memory',\n PSU: 'Power supply unit',\n};\n\n\nBoth Partial and Record are built in mapped types; you can read more about them in the inline TypeScript handbook links.\n\nHope that helps; good luck!\n\nPlayground link to code",
2020-02-23T19:24:48
Jackson :
You can use an interface to define the object:\n\ninterface IComponentType {\n CPU?: string;\n Motherboard?: string;\n Memory?: string;\n PSU?: string;\n}\n\n\nSince componentTypeToLabel may not contain all the possible values, we can define them as optional in the interface using the ?.\n\nThen we can create the object with type:\n\nconst componentTypeToLabel:IComponentType = {\n CPU: 'Computer processing unit',\n Motherboard: 'Motherboard',\n Memory: 'Memory',\n PSU: 'Power supply unit',\n};\n",
2020-02-23T17:30:19